//
//  InvestmentViewController.m
//  SP2P
//
//  Created by EIMS-IOS on 16/1/12.
//  Copyright (c) 2016年 EIMS. All rights reserved.
//

#import "InvestmentViewController.h"
#import "InvestmentCell.h"
#import "InvestmentDetailViewController.h"
#import "CacheUtil.h"
#import "InvestmentModel.h"
#import "AddBankCardViewController.h"

@interface InvestmentViewController ()<HTTPClientDelegate,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate> {
    
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, copy  ) NSString      *cacheFileName;
@property (nonatomic, assign) BOOL          isLoading;
@property (nonatomic, assign) NSInteger     requestType;
@property (nonatomic, assign) NSInteger     currPage;
@property (nonatomic, assign) NSInteger     totalCount;


@end

@implementation InvestmentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (iOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    [self initNavigationBar];
    
   
    [self initView];
    [self initData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
}

#pragma mark - Action
- (void)tenderButtonClick:(UIButton *)button {
    if (AppDelegateInstance.userInfo.realName.length<=0 || !AppDelegateInstance.userInfo.hasBindCard) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您尚未进行实名认证" message:@"是否前去实名认证？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 7;
        [alert show];
        return;
    }
    
    NSInteger index = button.tag - 100;
    InvestmentModel *model = _dataArray[index];
    [self gotoInvestDetailWithModel:model];
}

- (void)gotoInvestDetailWithModel:(InvestmentModel *)model {
    if (AppDelegateInstance.userInfo == nil) {
        [ReLogin goLogin:self];
        return;
    }
    
    InvestmentDetailViewController *detail = [[InvestmentDetailViewController alloc] init];
    detail.hidesBottomBarWhenPushed = YES;
    detail.naviTitle = model.investmentName;
    detail.viewType = model.investmentType;
    detail.investmentId = model.investmentId;
    
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag==7 && buttonIndex==1) {
        //去实名认证
        AddBankCardViewController *addBankCard = [[AddBankCardViewController alloc] init];
        addBankCard.editType = 1;
        addBankCard.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:addBankCard animated:YES];
    }
}

#pragma mark - TableView
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(_dataArray.count>0){
    InvestmentModel *model = _dataArray[indexPath.section];
    [self gotoInvestDetailWithModel:model];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count>0?_dataArray.count:1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataArray.count) {
        static NSString *cellID = @"cellID";
        InvestmentCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"InvestmentCell" owner:self options:nil][0];
            cell.backgroundColor = KbackgroundColor;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell refreshCellWithModel:_dataArray[indexPath.section]];
        cell.tenderButton.tag = 100 + indexPath.section;
        [cell.tenderButton addTarget:self action:@selector(tenderButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, KAdaptNum(120));
        return cell;
    }else {
        
        EmptyTableViewCell *cell = [[EmptyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"emptyCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.backgroundColor = KbackgroundColor;
        cell._isLoading = _isLoading;
        
        cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, _tableView.frame.size.height);
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 15.0f;
    }
    return 7.5f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 7.5f;
}


#pragma mark - Data
- (void)initData {
    _dataArray = [NSMutableArray array];
    
   // [_dataArray addObjectsFromArray:@[@"",@"",@""]];
}

- (void)requestData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"506" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:[NSString stringWithFormat:@"%ld",(long)_currPage] forKey:@"currPage"];
    
    _cacheFileName = [CacheUtil creatCacheFileName:parameters];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma - HTTPClientDelegate 网络数据回调代理
- (void)startRequest {
    _isLoading = YES;
}

// 返回成功
-(void) httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    [self processData:obj isCache:NO];// 读取当前请求到的数据
}

- (void)processData:(NSDictionary *)dataDics isCache:(BOOL) isCache {
    DLOG(@"dataDics is %@",dataDics);
    if ([[NSString stringWithFormat:@"%@",[dataDics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        if(!isCache){
            // 非缓存数据，且返回的是-1 成功的数据，才更新数据源，否则不保存
            NSString *path =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
            NSString *cachePath = [path stringByAppendingPathComponent:_cacheFileName];// 合成归档保存的完整路径
            [NSKeyedArchiver archiveRootObject:dataDics toFile:cachePath];// 数据归档，存取缓存
        }
        
        if (_currPage == 1) {
            [_dataArray removeAllObjects];
        }
        
        
        if ([dataDics objectForKey:@"list"] && ![[dataDics objectForKey:@"list"] isKindOfClass:[NSNull class]]) {
            NSArray *list = [dataDics objectForKey:@"list"];
            for (NSDictionary *subDict in list) {
                InvestmentModel *model = [InvestmentModel objectWithKeyValues:subDict];
                model.investmentId = [NSString stringWithFormat:@"%@",subDict[@"id"]];
                switch (model.period) {
                    case 3:
                    {
                        model.investmentType = 1;
                        model.investmentName = @"季季增";
                    }
                        break;
                    case 6:
                    {
                        model.investmentType = 2;
                        model.investmentName = @"半年赢";
                    }
                        break;
                        
                    case 12:
                    {
                        model.investmentType = 3;
                        model.investmentName = @"年年丰";
                    }
                        break;
                        
                        
                    default:
                        model.investmentType = 1;
                        model.investmentName = @"季季增";
                        break;
                }
                [_dataArray addObject:model];
                
            }
        }
        
        
        if (!isCache) {
            // 非缓存数据才显示隐藏
            [self hiddenRefreshView];
        }
        
        [_tableView reloadData];
        
    }else {
        if (!isCache) {
            // 非缓存数据才显示错误
            [self hiddenRefreshView];
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", [dataDics objectForKey:@"msg"]]];
        }
    }
}

// 返回失败
- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    
    [self hiddenRefreshView];
    [self readCache];
     _isLoading = NO;
}

// 无可用的网络
- (void)networkError {
    [self hiddenRefreshView];
    [self readCache];
    _isLoading = NO;
}

#pragma 加载缓存数据
-(void) readCache
{
    // 刷新前先加载缓存数据
    NSString *path =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSString *cachePath = [path stringByAppendingPathComponent:_cacheFileName];// 合成归档保存的完整路径
    NSDictionary *dics = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePath];// 上一次缓存数据
    [self processData:dics isCache:YES];// 读取上一次成功缓存的数据
}

#pragma mark - 刷新
- (void)headerRereshing {
    _currPage = 1;
    [self requestData];
    
}

- (void)footerRereshing {
    _currPage ++;
    [self requestData];
}

- (void)hiddenRefreshView {
    if (!_tableView.mj_header.hidden) {
        [_tableView.mj_header endRefreshing];
    }
    if (!_tableView.mj_footer.hidden) {
        [_tableView.mj_footer endRefreshing];
    }
}

#pragma mark - View
- (void)initView {
    _tableView = [UITableView tableViewWithFrmae:RECTMAKE(0, 0, MSWIDTH, MSHIGHT - 64 - 49) backgroundColor:KbackgroundColor delegate:self dataSource:self tableViewStyle:UITableViewStyleGrouped separatorStyle:UITableViewCellSeparatorStyleNone superview:self.view];

     _tableView.mj_header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    // 自动刷新(一进入程序就下拉刷新)
    //    [self.tableView headerBeginRefreshing];
     [_tableView.mj_header beginRefreshing];
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    _tableView.mj_footer = [MJRefreshBackNormalFooter  footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
}

#pragma mark - Navigation
- (void)initNavigationBar
{
    self.title = NSLocalizedString(@"Tab_Investment", nil);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
